package com.example.archive.repository.elasticsearch;

import com.example.archive.entity.ArchiveDocument;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Elasticsearch档案文档Repository
 * 提供档案文档的全文搜索功能
 */
@Repository
public interface ArchiveDocumentRepository extends ElasticsearchRepository<ArchiveDocument, String> {
    
    /**
     * 根据标题搜索档案
     */
    List<ArchiveDocument> findByTitleContaining(String title);
    
    /**
     * 根据档案类型搜索
     */
    List<ArchiveDocument> findByArchiveType(String archiveType);
    
    /**
     * 根据安全级别搜索
     */
    List<ArchiveDocument> findBySecurityLevel(String securityLevel);
    
    /**
     * 根据状态搜索
     */
    List<ArchiveDocument> findByStatus(String status);
    
    /**
     * 多字段全文搜索
     * 搜索标题、物理位置、OCR内容、自动分类、自动标签
     */
    @Query("{\"bool\": {\"should\": [" +
           "{\"match\": {\"title\": {\"query\": \"?0\", \"boost\": 3.0}}}," +
           "{\"match\": {\"physicalLocation\": {\"query\": \"?0\", \"boost\": 2.0}}}," +
           "{\"match\": {\"ocrContent\": {\"query\": \"?0\", \"boost\": 2.5}}}," +
           "{\"match\": {\"autoCategory\": {\"query\": \"?0\", \"boost\": 1.5}}}," +
           "{\"match\": {\"autoTags\": {\"query\": \"?0\", \"boost\": 1.5}}}" +
           "]}}")
    Page<ArchiveDocument> searchByMultipleFields(String searchTerm, Pageable pageable);
    
    /**
     * 根据可见范围和全文搜索
     */
    @Query("{\"bool\": {\"must\": [" +
           "{\"bool\": {\"should\": [" +
           "{\"term\": {\"visibleScope\": \"all\"}}," +
           "{\"term\": {\"visibleScope\": \"?1\"}}" +
           "]}}," +
           "{\"bool\": {\"should\": [" +
           "{\"match\": {\"title\": {\"query\": \"?0\", \"boost\": 3.0}}}," +
           "{\"match\": {\"physicalLocation\": {\"query\": \"?0\", \"boost\": 2.0}}}," +
           "{\"match\": {\"ocrContent\": {\"query\": \"?0\", \"boost\": 2.5}}}," +
           "{\"match\": {\"autoCategory\": {\"query\": \"?0\", \"boost\": 1.5}}}," +
           "{\"match\": {\"autoTags\": {\"query\": \"?0\", \"boost\": 1.5}}}" +
           "]}}" +
           "]}}")
    Page<ArchiveDocument> searchByMultipleFieldsWithVisibilityScope(String searchTerm, String userId, Pageable pageable);
} 